///  @explain
///  @author dongqiangbin
///  @create time 2023/11/29 13:25.

import 'dart:isolate';
import 'package:dio/dio.dart' as the_dio;
import 'package:isolate/isolate.dart';
import 'utils/ly_log.dart';
import '../network/base_response.dart';

final Future<LoadBalancer> loadBalancerCreator = LoadBalancer.create(3, IsolateRunner.spawn);

class IsolateMessage {}

class LYIsolateNetworkManager {
  static Future<BaseResponse> ordersList(String? accessToken, String? deviceId) async {
    final ReceivePort receivePort = ReceivePort();
    final LoadBalancer lb = await loadBalancerCreator;
    // 开启一个线程
    await lb.run<dynamic, SendPort>(_parsingInIsolate, receivePort.sendPort);
    final SendPort sendPort = await receivePort.first;
    final ReceivePort resultPort = ReceivePort();
    sendPort.send(_ParseMessageProtocol(resultPort.sendPort, deviceId, accessToken));
    var res = await resultPort.first;
    return res;
  }

  static Future<void> _parsingInIsolate(SendPort sendPort) async {
    final ReceivePort receivePort = ReceivePort();
    sendPort.send(receivePort.sendPort);
    receivePort.listen((message) async {
      try {
        final deviceId = message.deviceId;
        final accessToken = message.accessToken;
        final res = await http(accessToken, deviceId);
        BaseResponse sendData = parsedResult(res);
        message.sendPort.send(sendData);
      } catch (e) {
        LYLog.d('resolve报错:$e');
        try {
          BaseResponse sendData = errorResult(e);
          message.sendPort.send(sendData);
        } catch (e) {
          LYLog.d('resolve send error报错:$e');
        }
      }
    });
  }
}

Future<the_dio.Response> http(String? accessToken, String deviceId) async {
  the_dio.Dio api = the_dio.Dio();
  api.options.contentType = 'application/json';
  api.options.connectTimeout = const Duration(seconds: 30);
  api.options.receiveTimeout = const Duration(seconds: 30);
  api.options.headers = {
    "Content-Type": "application/json",
    "product": "reception",
    "device_id": deviceId,
    "ticket": deviceId,
    "access_token": accessToken,
  };
  // 日志拦截器
  // api.interceptors.add(the_dio.LogInterceptor(responseBody: true));
  final res = await api.post("https://api.ymlinks.com/user/admin/login",
      data: {"username": "test", "password": "666888"});
  return res;
}

class _ParseMessageProtocol {
  String? deviceId;
  String? accessToken;
  SendPort sendPort;
  _ParseMessageProtocol(this.sendPort, this.deviceId, this.accessToken);
}

BaseResponse parsedResult(response) {
  BaseResponse result;
  if (response.statusCode == 200) {
    LYLog.d(response);
    if (response.data['code'] == 200) {
      if (response.data['page'] != null && response.data['page'] != 'null') {
        result = BaseResponse(
            code: BaseResponseCode.success,
            msg: '数据请求成功啦!',
            success: true,
            result: response.data['result'],
            page: response.data['page']);
      } else {
        result = BaseResponse(
          code: BaseResponseCode.success,
          msg: '数据请求成功啦!',
          success: true,
          result: response.data['result'],
        );
      }
    } else {
      result = BaseResponse(
        code: response.data['code'],
        msg: "数据请求失败:${response.data['msg']}",
        success: false,
        result: null,
      );
    }
  } else {
    result = BaseResponse(
      code: response.data['code'],
      msg: "数据请求失败:${response.data['msg']}",
      success: false,
      result: null,
    );
  }
  return result;
}

BaseResponse errorResult(e) {
  BaseResponse sendData = BaseResponse(
    code: 0,
    msg: e.toString(),
    success: false,
    result: null,
  );
  return sendData;
}
